var util = (function(){
    return {
        ajax: function(url, method, success, error){
            var xhr = new XMLHttpRequest();
            xhr.open(method, url, true);
            xhr.setRequestHeader("accept", "application/json");
            xhr.onerror = error;
            xhr.onload = function(){
                if(xhr.status!= 200){
                    return error("status: " + xhr.status); 
                }
                var res = JSON.parse(xhr.responseText);
                if(res.code === 'SUCCESS'){
                    // debugger;
                    success(res.data);
                }
            }
            return xhr;
        },
        get: function(url, data){
            var that = this;
            if(!!data){
                var url = url + '?'+(that.object2string(data, '&', true)||'');
            }
            return new Promise(function(resolve, reject){

                var xhr = that.ajax(url, "GET", resolve, reject);
                xhr.send();
            })
        },
        post: function(url, data){
            var that = this;
            var data = that.object2string(data, "&", true)||"";
            return new Promise(function(resolve, reject){
                var xhr = that.ajax(url, "POST", resolve, reject);
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.send(data);
            });
        },
        postJSON: function(url, data){
            var that = this;
            var data = JSON.stringify(data);
            return new Promise(function(resolve, reject){
                var xhr = that.ajax(url, "POST", resolve, reject);
                xhr.setRequestHeader("Content-type", "application/json");
                xhr.send(data);
            });
        },
        postForm: function(url, formData){
            var that = this;
            return new Promise(function(resolve, reject){
                var xhr = that.ajax(url, "POST", resolve, reject);
                xhr.send(formData);
            })
        },
        putJSON:function(url, data){
            var that = this;
            var _data = "";
            if(data){
                _data = JSON.stringify(data);
            }
            return new Promise(function(resolve, reject){
                var xhr = that.ajax(url, "PUT", resolve, reject);
                xhr.setRequestHeader("Content-type","application/json");
                xhr.send(_data);
            })
        },
        type:function(obj){
            return Object.prototype.toString.call(obj).slice(8,-1).toLowerCase();  
        },

        object2string:function(obj,split,encode){
            if(!obj){
                return '';
            }
            var arr = [];
            for (var key in obj){
                if (!obj.hasOwnProperty(key)){
                    continue;
                }
                var value = obj[key];
                // 不处理function类型
                if (this.type(value) === 'function'){
                    continue;
                } else if(this.type(value) === 'date'){
                    value = value.getTime();
                } else if(this.type(value) === 'array'){
                    value = value.join(',');
                } else if(this.type(value) === 'object'){
                    value = JSON.stringify(value);
                }
                if(!!encode){
                    value =  encodeURIComponent(value);
                }
                arr.push(encodeURIComponent(key)+'='+value);
            }
            return arr.join(split||',')
        },

        setToken: function(token){
            localStorage.setItem('tkn', token);
        },
        getToken: function(){
            if(localStorage.getItem('tkn')){
                return true;
            }else{
                return false;
            }
        },
        clearToken: function(){
            localStorage.removeItem('tkn');
        },

        setCookie: function(name, value, expireDay){
            if(navigator.cookieEnabled){
				// 浏览器开启了cookie的功能
				// var cookie = name +"=" + encodeURIComponent(value)+";max-age=" + expireDay*24*3600;
				var cookie = name +"=" + escape(value)+";max-age=" + expireDay*24*3600;
				document.cookie = cookie;
			}
        },

        getCookie: function(name){
            var cookies = document.cookie;
			var _cookiearr = cookies.split("; "); //string为空的情况下，分割得到空数组
			for(var i=0; i<_cookiearr.length; i++){
				var _item = _cookiearr[i];
				var _itemarr = _item.split("=");
				if(_itemarr[0] === name){
					// return decodeURIComponent(_itemarr[1]); //最好decode一下，根据setCookie的值来决定吧,
                    return unescape(_itemarr[1]);    
                }
			}
			return "";
        },

        delCookie: function(name){
            document.cookie = name + "=" +escape(" ")+";max-age=-1";
        }
    }
})();
module.exports = util;